let log_list=[];//日志列表
let last_id=0;//最后一个日志id
let index=0;//当前渲染的日志id

$(e=>{
    getLog();
    resize();

    //总统计
    getRecord('1st',data=>{
        //今日观展人数
        peopleImg('todayJoinCount',data);
        //馆内当前人数
        peopleImg('nowCount',data);
        //人均参观时间
        $('#averageTime').text((data.averageTime/60).toFixed(1));
        //逗留最久人员
        stayPeople('longest',data);
        //逗留最短人员
        stayPeople('shortest',data);
    });

    //今日高峰
    getRecord('2nd',data=>{
        let format=name=>data.list.map(o=>(o[name]/1000).toFixed(3));
        peakHours({
            x:data.list.map(o=>o.time+':00'),
            into:format('joinCount'),
            out:format('leaveCount'),
            high:format('count')
        })
    });

    //单日逗留
    getRecord('3rd',data=>{
        let time=[2,4,6,8,10];
        //返回大于a小于b的数组占总数的比例
        let ratio=(arr,a=0,b)=>arr.map(o=>(o/3600).toFixed(2)).filter(o=>(o>=a&o<b) ).length*100/arr.length;
        //返回比例数组
        let func=arr=>[ratio(arr,0,time[0]),ratio(arr,time[0],time[1]),ratio(arr,time[1],time[2]),ratio(arr,time[2],time[3]),ratio(arr,time[3],time[4])];
        let obj={
            x:time,
            yesterday:func(data.yesterdayDurationList),
            today:func(data.todayDurationList)
        };
        dayStay(obj)
    });

    //单日访客
    getRecord('4th',data=>{
        let list=data.viewsList;
        if(list.length>10){//最后10个值
            list=list.filter((x,i)=>10-i<=0)
        }
        serverStatus({
            x:list.map(o=>o.day),
            y:list.map(o=>(o.count/1000).toFixed(3))
        })
    });

    //出入流量
    getRecord('5th',data=> {
        let list = data.flowList;
        let new_list = [];
        let length = 5;
        //随机拿length条数据
        if (list.length > length) {
            for (let i = length; i > 0; i--) {
                new_list.push(...list.splice(~~(Math.random() * list.length), 1))
            }
        }
        else new_list = list;
        let arr = [['name', 'amount']];
        //最大值
        let max = Math.max(...(new_list.map(o => (o.flow / 1000).toFixed(2))));
        for (let x of new_list) {
            arr.push([x.cameraName, (x.flow / 1000).toFixed(2)])
        }
        entranceTraffic({arr:arr,max:max})
    });

    //进出总量
    getRecord('6th',data=> {
        pieChart(charts[4],'进场方向',[data.intoCount,data.count]);
        pieChart(charts[5],'离场方向',[data.outCount,data.count]);
        pieChart(charts[6],'登记访客',[data.allJoinCount,50000],['#27ECB8','#1C5D52']);
    })
});

//定时渲染日志列表
setInterval(e=>{
    let x=log_list[index];
    if(x){
        let time=x.time.split(' ')[1] || '00:00:00';
        let pid=x.pid.substr(0,16) || '暂无id';
        $('#log_ul').append(`<li><div class="td1">${time}</div><div class="td2"><span class="es">${pid}</span> &nbsp;${x.description || '暂无描述'}</div></li>`).animate({scrollTop:log_ul.scrollHeight},500);
        //1入2出
        let name=x.direction==1?'.in':'.out';
        $(name+' .es').html(pid+`<time>${time}</time>`);
        let img=x.captureImage;
        if(img){
            if(x.captureImage.indexOf('base64')>-1) img=x.captureImage;
            else img='data:image/jpeg;base64,'+x.captureImage;
        }
        else img='img/avatar.png';
        $(name+' .headimg').css('background-image',`url(${img})`);
        index++;
    }
},1000);

//日期变动
setInterval(e=>{
    let d=new Date();
    let weekday=["日","一","二","三","四","五","六"];
    $('#now_time').html(`<small>${d.getFullYear()}年${d.getMonth()+1}月${d.getDate()}日 / 周${weekday[d.getDay()]}</small><time class="es">${d.toTimeString().split(' ')[0]}</time>`)
},1000);

window.onresize=()=>{resize()};

//禁用右键
document.oncontextmenu = function(){
    event.returnValue = false;
};

//获取日志列表
let getLog=()=>{
    ajax('getNowRecord',{id:last_id,nowTime:new Date().toLocaleDateString().replace(/\//g,'-')+' '+new Date().toTimeString().split(' ')[0]},v=>{
        if(v.code==0){
            let data=v.data;
            if(data.length>0){
                log_list.push(...data);
                //最后一个日志id
                last_id=data[data.length-1].id
            }
        }
        setTimeout(getLog,5000)
    });
};
